
import { _decorator, Component, Node, SpriteFrame, Prefab, instantiate, PageView, Sprite } from 'cc';
import GameData from '../../Script/Common/GameData';
import GlobalPool, { customPoolScript } from '../../Script/Common/GlobalPool';
import Loader from '../../Script/Common/Loader';
import yyComponent from '../../Script/Common/yyComponent';
import { EventType } from '../../Script/GameSpecial/GameEventType';
import { GlobalEnum } from '../../Script/GameSpecial/GlobalEnum';
import { Item } from './Item';
const { ccclass, property } = _decorator;

enum btnType {
    skin = 0,
    hat = 1,
    weapon = 2,
}

@ccclass('ShopUI')
export class ShopUI extends yyComponent {
    /**场景/UI类型 */
    public get uiType() { return GlobalEnum.UI.shop; }

    @property(Prefab)
    item: Prefab = null;
    //#region 脚本流程
    public init(data?) {
        this.initRoleLayer();
        if (undefined !== data) {
            this.setData(data);
        }
        this.loadData();
        this.onEvents();
        GlobalPool.createPool(this.item.data.name, this.item, this.item.data.name);
    }
    protected setData(data) {

    }
    public reset() {
        this.resetRoleLayer();
    }

    public show(data?: { data: any, config: any }) {
        this.reset();
        this.onEvents();
        this.node.active = true;
        if (undefined !== data && undefined !== data.data) {
            this.setData(data.data);
        }
        this.nowCard = GlobalEnum.GoodsType.skin;
        this.chioseBtn(btnType.skin);
        this.updateCard();
        this.addRoleLayer();
        this.emit(EventType.LevelEvent.changeGoldPos, false);
    }
    GoodsData: {};
    protected loadData() {
        this.GoodsData = GameData.getData("GoodsData");
    }
    onEvents() {
        this.on(EventType.LevelEvent.goodsUSE, this.goodsUSE, this);
    }
    goodsUSE() {
        for (let i = 0; i < this.items.length; i++) {
            this.items[i].refresh();
        }
    }
    //#endregion

    //#region 商品清单
    nowCard = GlobalEnum.GoodsType.skin;
    @property([Node])
    cards: Node[] = [];
    items: Item[] = [];
    protected updateCard() {
        this.resetCard();
        this.setCard();
    }

    protected setCard() {
        let num = this.getItemsNum();
        this.madeCard(num);
        // this.addItem(num);
        this.goalNum = num;
        this.setpAddItem(true);
    }
    @property(PageView)
    pageManage: PageView = null;
    protected getItemsNum() {
        let cardData = this.GoodsData[this.nowCard];
        let num = cardData["num"];
        return num;
    }
    protected madeCard(num) {
        let page = Math.ceil(num / 6);
        let card = this.cards[0];
        while (this.cards.length < page) {
            let newNode = instantiate(card);

            this.pageManage.addPage(newNode);
            this.cards.push(newNode);
        }
    }

    weaponList = ["katana", "captain", "claw", "gun", "hunter", "knife", "trapper"];
    // weaponList = ["katana", "captain", "claw", "gun", "hunter", "knife"];
    goalNum = 0;
    nowNum = 0;
    //根据一定步长定量加载Item，分摊性能消耗；
    protected setpAddItem(isInit: Boolean) {
        if (!!isInit) {
            this.nowNum = 0;
        }
        let indexCard = Math.floor(this.nowNum / 6);
        let card = this.cards[indexCard];
        if (!card) {
            return;
        }
        for (let i = 0; i < 6; i++) {
            let signNode = card.getChildByName(String(i + 1));
            let newItem = GlobalPool.get(this.item.data.name);
            signNode.addChild(newItem);
            this.items.push(newItem[customPoolScript]);

            this.addItem();

            this.nowNum++;
            if (this.nowNum >= this.goalNum) {
                return;
            }
        }
        setTimeout(() => {
            this.setpAddItem(false);
        }, 400);
    }
    //根据nowNum添加Item，并设置数据
    protected addItem() {
        if (this.nowCard != GlobalEnum.GoodsType.weapon) {
            let cardData = this.GoodsData[this.nowCard];
            this.items[this.nowNum].setData(cardData[String(this.nowNum + 1)]);
        } else {
            let weapomData = this.GoodsData[this.nowCard];
            let itemData = null;
            let cutNum = this.nowNum;
            for (let i = 0; i < this.weaponList.length; i++) {
                let data = weapomData[this.weaponList[i]];
                if (cutNum < data["num"]) {
                    itemData = data[(cutNum + 1).toString()];
                    break;
                } else {
                    cutNum -= data["num"];
                }
            }
            this.items[this.nowNum].setData(itemData);
        }
    }
    //重置商品Card,删除全部商品，只保留一个样板用商品架（Card);
    protected resetCard() {
        if (this.items.length != 0) {
            this.releaseItem();
        }
        if (this.cards.length > 1) {
            this.releaseCard();
        }
    }
    protected releaseItem() {
        while (this.items.length > 0) {
            let item = this.items.pop();
            GlobalPool.put(item.node);
        }
    }
    protected releaseCard() {
        while (this.cards.length > 1) {
            let card = this.cards.pop();
            this.pageManage.removePage(card);
            card.destroy();
        }
    }

    @property([Sprite])
    btnSprs: Sprite[] = [];
    @property(SpriteFrame)
    defaultImg: SpriteFrame = null;
    @property(SpriteFrame)
    chioseImg: SpriteFrame = null;
    chioseBtn(num) {
        for (let i = 0; i < this.btnSprs.length; i++) {
            if (i == num) {
                this.btnSprs[i].spriteFrame = this.chioseImg;
            } else {
                this.btnSprs[i].spriteFrame = this.defaultImg;
            }
        }
    }

    protected onBtnSkin() {
        this.playClickBtn();
        this.nowCard = GlobalEnum.GoodsType.skin;
        this.chioseBtn(btnType.skin);
        this.updateCard();
    }
    protected onBtnHat() {
        this.playClickBtn();
        this.nowCard = GlobalEnum.GoodsType.hat;
        this.chioseBtn(btnType.hat);
        this.updateCard();
    }
    protected onBtnWeapon() {
        this.playClickBtn();
        this.nowCard = GlobalEnum.GoodsType.weapon;
        this.chioseBtn(btnType.weapon);
        this.updateCard();
    }

    //#endregion

    //#region 角色模型
    @property(Node)
    protected roleLayer: Node = null;
    protected initRoleLayer() { }
    protected resetRoleLayer() {
        GlobalPool.putAllChildren(this.roleLayer);
    }
    protected addRoleLayer() {
        let node = GlobalPool.get("ShopRole");
        if (!!node) {
            this.roleLayer.addChild(node);
        } else {
            Loader.loadBundle("Role", () => {
                Loader.loadBundleRes("Role", "Prefab/ShopRole", (res) => {
                    GlobalPool.createPool(res.data.name, res, res.data.name);
                    if (this.node.active && this.roleLayer.children.length == 0) {
                        let role = GlobalPool.get("ShopRole");
                        this.roleLayer.addChild(role);
                    }
                }, Prefab, false);
            }, false, false);
        }
    }
    //#endregion

    public onBtnExit() {
        this.playClickBtn();
        this.emit(EventType.Common.UIEvent.exit, this.uiType);
        this.emit(EventType.LevelEvent.changeGoldPos, true);
    }

}